package com.blrs.service.collaborative.impl;

import java.sql.Timestamp;
import java.util.*;


import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.uuid.UUID;
import com.blrs.domain.CollaborativeManagement;

import com.blrs.domain.SupplierInfo;
import com.blrs.mapper.CollaborationApprovalMapper;
import com.blrs.mapper.CollaborativeManagementMapper;

import com.blrs.mapper.SupplierInfoMapper;
import com.blrs.service.collaborative.ICollaborativeManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-11
 */
@Service
public class CollaborativeManagementServiceImpl implements ICollaborativeManagementService {
    @Autowired
    private CollaborativeManagementMapper collaborativeManagementMapper;
    @Autowired
    private SupplierInfoMapper supplierInfoMapper;
@Autowired
private CollaborationApprovalMapper collaborationApprovalMapper;
    /**
     * 查询【请填写功能名称】
     *
     * @param collaborativeId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public CollaborativeManagement selectCollaborativeManagementByCollaborativeId(String collaborativeId) {
        return collaborativeManagementMapper.selectCollaborativeManagementByCollaborativeId(collaborativeId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param collaborativeManagement 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<CollaborativeManagement> selectCollaborativeManagementList(CollaborativeManagement collaborativeManagement) {
        //用于客户管理查询判断,如果getOrgId不为空的话 代表是从客户管理调用
        // 传的客户的机构id
        if (StringUtils.isEmpty(collaborativeManagement.getOrgId())) {
            collaborativeManagement.setOrgId(SecurityUtils.getOrgId().toString());
        }
        return collaborativeManagementMapper.selectCollaborativeManagementList(collaborativeManagement);
    }

    @Override
    public List<CollaborativeManagement> selectCollaborativeManagementListTwo(CollaborativeManagement collaborativeManagement) {
        collaborativeManagement.setRecipientId(SecurityUtils.getOrgId().toString());
        return collaborativeManagementMapper.selectCollaborativeManagementListTwo(collaborativeManagement);
    }

    @Override
    public List selectCollaborativeManagementInfoList(CollaborativeManagement collaborativeManagement) {
        List<CollaborativeManagement> collaborativeManagements  = collaborativeManagementMapper.selectCollaborativeManagementListTwo(collaborativeManagement);
        List<Object> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("listitem",collaborativeManagements);
        list.add(map);
        return list;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param collaborativeManagement 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertCollaborativeManagement(CollaborativeManagement collaborativeManagement) {
        boolean flag = collaborativeManagement.getRecipientId().contains(",");
        int count = 0;
        if (flag) {
            String[] recipientIds = collaborativeManagement.getRecipientId().split(",");
            String[] recipientNames = collaborativeManagement.getRecipientName().split(",");
            for (int i = 0; i < recipientIds.length; i++) {
                CollaborativeManagement management = new CollaborativeManagement();
                management.setInitiatorId(SecurityUtils.getOrgId().toString());
                management.setRecipientId(recipientIds[i]);
                CollaborativeManagement management1 = new CollaborativeManagement();
                management1.setInitiatorId(recipientIds[i]);
                management1.setRecipientId(SecurityUtils.getOrgId().toString());
                List<CollaborativeManagement> managementList = collaborativeManagementMapper.selectCollaborativeManagementListDuplicate(management);
                List<CollaborativeManagement> managementList1 = collaborativeManagementMapper.selectCollaborativeManagementListDuplicate(management1);
                if (managementList.size() > 0 && "0".equals(managementList.get(0).getDelFlag())&& "2".equals(managementList.get(0).getState())) {
                    throw new RuntimeException("已经与" + collaborativeManagement.getRecipientName() + "建立了合作，不可重复建立！");
                } else if (managementList1.size() > 0 && "0".equals(managementList1.get(0).getDelFlag())&& "2".equals(managementList1.get(0).getState())) {
                    throw new RuntimeException("已经与" + managementList1.get(0).getInitiatorName() + "建立了合作，不可重复建立！");
                } else if(managementList.size() > 0 && "0".equals(managementList.get(0).getDelFlag())&& "3".equals(managementList.get(0).getState())){
                    throw new RuntimeException("与" + collaborativeManagement.getRecipientName() + "合作申请没通过，请到列表再次提交！");
                }else if(managementList.size() > 0 && "0".equals(managementList.get(0).getDelFlag())&& "1".equals(managementList.get(0).getState())){
                    throw new RuntimeException("与" + collaborativeManagement.getRecipientName() + "的合作正在审核中，不可重复建立！");
                }else if(managementList1.size() > 0 && "0".equals(managementList1.get(0).getDelFlag())&& "1".equals(managementList1.get(0).getState())){
                    throw new RuntimeException(managementList1.get(0).getInitiatorName() + "已提交合作申请，请去审核建立！");
                }else {
                    if (managementList.size()> 0 && "1".equals(managementList.get(0).getDelFlag())) {
                        collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(managementList.get(0).getCollaborativeId());
                        collaborationApprovalMapper.deleteCollaborationApprovalByCollaborativeId(managementList.get(0).getCollaborativeId());
                    }
                    if (managementList1.size()> 0 && "1".equals(managementList1.get(0).getDelFlag())) {
                        collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(managementList1.get(0).getCollaborativeId());
                        collaborationApprovalMapper.deleteCollaborationApprovalByCollaborativeId(managementList1.get(0).getCollaborativeId());
                    }
                    if(managementList1.size()> 0 && "3".equals(managementList1.get(0).getState())){
                        collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(managementList1.get(0).getCollaborativeId());
                        collaborationApprovalMapper.deleteCollaborationApprovalByCollaborativeId(managementList1.get(0).getCollaborativeId());
                    }
                    management.setCollaborativeId(UUID.randomUUID().toString());
                    management.setInitiatorName(SecurityUtils.getOrgName());
                    management.setRecipientName(recipientNames[i]);
                    management.setCooperationReason(collaborativeManagement.getCooperationReason());
                    management.setState("1");
                    management.setCreateId(SecurityUtils.getUserId().toString());
                    management.setCreateName(SecurityUtils.getUsername());
                    management.setCreateTime(new Timestamp(new Date().getTime()));
                    management.setOperateTime(new Timestamp(new Date().getTime()));
                    management.setOperateName(SecurityUtils.getUsername());
                    management.setOperateId(SecurityUtils.getUserId());
                    management.setOrganizationId(SecurityUtils.getOrgId());
                    management.setOrganizationName(SecurityUtils.getOrgName());
                    management.setDepartmentId(SecurityUtils.getDeptId());
                    management.setBelongTo(SecurityUtils.getOrgId());
                    management.setDelFlag("0");
                    count = collaborativeManagementMapper.insertCollaborativeManagement(management);
                }
            }
        } else {
            CollaborativeManagement management = new CollaborativeManagement();
            management.setInitiatorId(SecurityUtils.getOrgId().toString());
            management.setRecipientId(collaborativeManagement.getRecipientId());
            CollaborativeManagement management1 = new CollaborativeManagement();
            management1.setInitiatorId(collaborativeManagement.getRecipientId());
            management1.setRecipientId(SecurityUtils.getOrgId().toString());
            List<CollaborativeManagement> managementList = collaborativeManagementMapper.selectCollaborativeManagementListDuplicate(management);
            List<CollaborativeManagement> managementList1 = collaborativeManagementMapper.selectCollaborativeManagementListDuplicate(management1);
            if (managementList.size() > 0 && "0".equals(managementList.get(0).getDelFlag())&& "2".equals(managementList.get(0).getState())) {
                throw new RuntimeException("已经与" + collaborativeManagement.getRecipientName() + "建立了合作，不可重复建立！");
            } else if (managementList1.size() > 0 && "0".equals(managementList1.get(0).getDelFlag())&& "2".equals(managementList1.get(0).getState())) {
                throw new RuntimeException("已经与" + managementList1.get(0).getInitiatorName() + "建立了合作，不可重复建立！");
            } else if(managementList.size() > 0 && "0".equals(managementList.get(0).getDelFlag())&& "3".equals(managementList.get(0).getState())){
                throw new RuntimeException("与" + collaborativeManagement.getRecipientName() + "合作申请没通过，请到列表再次提交！");
            }else if(managementList.size() > 0 && "0".equals(managementList.get(0).getDelFlag())&& "1".equals(managementList.get(0).getState())){
                throw new RuntimeException("与" + collaborativeManagement.getRecipientName() + "的合作正在审核中，不可重复建立！");
            }else if(managementList1.size() > 0 && "0".equals(managementList1.get(0).getDelFlag())&& "1".equals(managementList1.get(0).getState())){
                throw new RuntimeException(managementList1.get(0).getInitiatorName() + "已提交合作申请，请去审核建立！");
            }else {
                if (managementList.size()> 0 && "1".equals(managementList.get(0).getDelFlag())) {
                    collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(managementList.get(0).getCollaborativeId());
                    collaborationApprovalMapper.deleteCollaborationApprovalByCollaborativeId(managementList.get(0).getCollaborativeId());
                }
                if (managementList1.size()> 0 && "1".equals(managementList1.get(0).getDelFlag())) {
                    collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(managementList1.get(0).getCollaborativeId());
                    collaborationApprovalMapper.deleteCollaborationApprovalByCollaborativeId(managementList1.get(0).getCollaborativeId());
                }
                if(managementList1.size()> 0 && "3".equals(managementList1.get(0).getState())){
                    collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(managementList1.get(0).getCollaborativeId());
                    collaborationApprovalMapper.deleteCollaborationApprovalByCollaborativeId(managementList1.get(0).getCollaborativeId());
                }
                collaborativeManagement.setCollaborativeId(UUID.randomUUID().toString());
                collaborativeManagement.setInitiatorId(SecurityUtils.getOrgId().toString());
                collaborativeManagement.setInitiatorName(SecurityUtils.getOrgName());
                collaborativeManagement.setRecipientName(collaborativeManagement.getRecipientName());
                collaborativeManagement.setState("1");
                management.setCooperationReason(collaborativeManagement.getCooperationReason());
                collaborativeManagement.setCreateId(SecurityUtils.getUserId().toString());
                collaborativeManagement.setCreateName(SecurityUtils.getUsername());
                collaborativeManagement.setCreateTime(new Timestamp(new Date().getTime()));
                collaborativeManagement.setOperateTime(new Timestamp(new Date().getTime()));
                collaborativeManagement.setOperateName(SecurityUtils.getUsername());
                collaborativeManagement.setOperateId(SecurityUtils.getUserId());
                collaborativeManagement.setOrganizationId(SecurityUtils.getOrgId());
                collaborativeManagement.setOrganizationName(SecurityUtils.getOrgName());
                collaborativeManagement.setDepartmentId(SecurityUtils.getDeptId());
                collaborativeManagement.setBelongTo(SecurityUtils.getOrgId());
                collaborativeManagement.setDelFlag("0");
                count = collaborativeManagementMapper.insertCollaborativeManagement(collaborativeManagement);
            }
        }
        return count;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param collaborativeManagement 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateCollaborativeManagement(CollaborativeManagement collaborativeManagement) {
        CollaborativeManagement management = collaborativeManagementMapper.selectCollaborativeManagementByCollaborativeId(collaborativeManagement.getCollaborativeId());
        if ("end".equals(collaborativeManagement.getSign())) {
            management.setState("4");
            management.setDelFlag("1");
            SupplierInfo infoList = supplierInfoMapper.selectEnterpriseNameByName(management.getInitiatorName(),management.getRecipientId());
            if(infoList!=null){
                if(StringUtils.isNotEmpty(infoList.getType())){
                    SupplierInfo lier = new SupplierInfo();
                    lier.setEnterpriseId(infoList.getEnterpriseId());
                    lier.setEnterpriseName(infoList.getEnterpriseName());
                    lier.setBelongTo(infoList.getBelongTo());
                    lier.setIndustryType(infoList.getIndustryType());
                    lier.setClassificationId("650c44e1-b575-4b62-9d54-1ba9d1e8abb7");
                    lier.setEnterpriseNature(infoList.getEnterpriseNature());
                    lier.setEnterpriseNo(infoList.getEnterpriseNo());
                    lier.setRegisteredCapital(infoList.getRegisteredCapital());
                    lier.setEnterpriseSource(infoList.getEnterpriseSource());
                    lier.setEnterpriseAddress(infoList.getEnterpriseAddress());
                    lier.setIndustry(infoList.getIndustry());
                    lier.setLegalRepresentative(infoList.getLegalRepresentative());
                    lier.setEstablishmentDate(infoList.getEstablishmentDate());
                    lier.setAdministrativeArea(infoList.getAdministrativeArea());
                    lier.setContacts(infoList.getContacts());
                    lier.setTelephone(infoList.getTelephone());
                    lier.setDevelopmentId(infoList.getDevelopmentId());
                    lier.setDevelopmentManager(infoList.getDevelopmentManager());
                    lier.setTransactionId(infoList.getTransactionId());
                    lier.setBusinessManager(infoList.getBusinessManager());
                    lier.setStatus(infoList.getStatus());
                    lier.setBusinessScope(infoList.getBusinessScope());
                    lier.setCreationId(infoList.getCreationId());
                    lier.setCreationName(infoList.getCreationName());
                    lier.setCreationTime(infoList.getCreationTime());
                    lier.setOperateId(infoList.getOperateId());
                    lier.setOperateTime(infoList.getOperateTime());
                    lier.setDepartmentId(infoList.getDepartmentId());
                    lier.setDepartmentName(infoList.getDepartmentName());
                    lier.setOrganizationId(infoList.getOrganizationId());
                    lier.setOrganizationName(infoList.getOrganizationName());
                    lier.setDelFlag("0");
                    lier.setType(infoList.getType());
                    supplierInfoMapper.deleteSupplierInfoByEnterpriseId(infoList.getEnterpriseId());
                    supplierInfoMapper.insertSupplierInfo(lier);
                }else{
                    supplierInfoMapper.deleteSupplierInfoByEnterpriseId(infoList.getEnterpriseId());
                }
            }
            SupplierInfo info = new SupplierInfo();
            info.setEnterpriseName(management.getRecipientName());
            info.setBelongTo(management.getInitiatorId());
            SupplierInfo supplierInfoList = supplierInfoMapper.selectEnterpriseNameByName(management.getRecipientName(),management.getInitiatorId());
            if(supplierInfoList!=null){
                if(StringUtils.isNotEmpty(supplierInfoList.getType())){
                    SupplierInfo supplierInfo = new SupplierInfo();
                    supplierInfo.setEnterpriseId(supplierInfoList.getEnterpriseId());
                    supplierInfo.setEnterpriseName(supplierInfoList.getEnterpriseName());
                    supplierInfo.setBelongTo(supplierInfoList.getBelongTo());
                    supplierInfo.setIndustryType(supplierInfoList.getIndustryType());
                    supplierInfo.setClassificationId("650c44e1-b575-4b62-9d54-1ba9d1e8abb7");
                    supplierInfo.setEnterpriseNature(supplierInfoList.getEnterpriseNature());
                    supplierInfo.setEnterpriseNo(supplierInfoList.getEnterpriseNo());
                    supplierInfo.setRegisteredCapital(supplierInfoList.getRegisteredCapital());
                    supplierInfo.setEnterpriseSource(supplierInfoList.getEnterpriseSource());
                    supplierInfo.setEnterpriseAddress(supplierInfoList.getEnterpriseAddress());
                    supplierInfo.setIndustry(supplierInfoList.getIndustry());
                    supplierInfo.setLegalRepresentative(supplierInfoList.getLegalRepresentative());
                    supplierInfo.setEstablishmentDate(supplierInfoList.getEstablishmentDate());
                    supplierInfo.setAdministrativeArea(supplierInfoList.getAdministrativeArea());
                    supplierInfo.setContacts(supplierInfoList.getContacts());
                    supplierInfo.setTelephone(supplierInfoList.getTelephone());
                    supplierInfo.setDevelopmentId(supplierInfoList.getDevelopmentId());
                    supplierInfo.setDevelopmentManager(supplierInfoList.getDevelopmentManager());
                    supplierInfo.setTransactionId(supplierInfoList.getTransactionId());
                    supplierInfo.setBusinessManager(supplierInfoList.getBusinessManager());
                    supplierInfo.setStatus(supplierInfoList.getStatus());
                    supplierInfo.setBusinessScope(supplierInfoList.getBusinessScope());
                    supplierInfo.setCreationId(supplierInfoList.getCreationId());
                    supplierInfo.setCreationName(supplierInfoList.getCreationName());
                    supplierInfo.setCreationTime(supplierInfoList.getCreationTime());
                    supplierInfo.setOperateId(supplierInfoList.getOperateId());
                    supplierInfo.setOperateTime(supplierInfoList.getOperateTime());
                    supplierInfo.setDepartmentId(supplierInfoList.getDepartmentId());
                    supplierInfo.setDepartmentName(supplierInfoList.getDepartmentName());
                    supplierInfo.setOrganizationId(supplierInfoList.getOrganizationId());
                    supplierInfo.setOrganizationName(supplierInfoList.getOrganizationName());
                    supplierInfo.setDelFlag("0");
                    supplierInfo.setType(supplierInfoList.getType());
                    supplierInfoMapper.deleteSupplierInfoByEnterpriseId(supplierInfoList.getEnterpriseId());
                    supplierInfoMapper.insertSupplierInfo(supplierInfo);
                }else{
                    supplierInfoMapper.deleteSupplierInfoByEnterpriseId(supplierInfoList.getEnterpriseId());
                }
            }
        } else {
            management.setState("1");
        }
        return collaborativeManagementMapper.updateCollaborativeManagement(management);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param collaborativeIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCollaborativeManagementByCollaborativeIds(String[] collaborativeIds) {
        return collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeIds(collaborativeIds);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param collaborativeId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCollaborativeManagementByCollaborativeId(String collaborativeId) {
        return collaborativeManagementMapper.deleteCollaborativeManagementByCollaborativeId(collaborativeId);
    }

    @Override
    public int selectCollaborativeInfoNumber(Long organizationId) {
        return collaborativeManagementMapper.selectCollaborativeInfoNumber(organizationId);
    }

    @Override
    public List selectCollaborativeInfoListByType(CollaborativeManagement collaborativeManagement) {
        List<CollaborativeManagement> collaborativeManagements  = collaborativeManagementMapper.selectCollaborativeInfoListByType(collaborativeManagement);
        List<Object> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("listitem",collaborativeManagements);
        list.add(map);
        return list;
    }

    @Override
    public int checkOrganizationHasCollaborative(Long organizationId) {
        System.out.println(SecurityUtils.getOrgId());
        int i = collaborativeManagementMapper.checkOrganizationHasCollaborative(organizationId, SecurityUtils.getOrgId());
        System.out.println(i);
        return i;
    }


}
